class_name RoundSys
extends System

const CATCH_READ_C = ["Ext", "GlobalRound", "RoundFighter", "RoundCountC", "RoundStateC"]

var state = false
var catch_read := []


func _init():
	system_name = "RoundSys"
	listen_modify("ready", "GlobalReady", ["GlobalReady", "GlobalRound"])
	listen_create("add", "Entities", ["RoundCountC", "RoundOrderC", "RoundStateC"])
	listen_modify("round_over", "RoundStateC", ["RoundStateC"])


func _system_ready():
	catch_read = world.query_manager.fetch_components(CATCH_READ_C)


func _system_process(_delta):
	if not state:
		return
	var ext = catch_read[0].data as Ext
	var round_count = catch_read[1].data.count
	var find_id = 0
	var max_order = 0
	var round_count_multi = catch_read[3]

	for id in round_count_multi.data:
		var rc = round_count_multi.get(id) as RoundCount
		if rc.value >= round_count:
			continue
		if not ext.is_alive(id):
			continue
		var order = ext.get_round_order(id)
		if not order:
			continue
		if order < max_order:
			continue
		find_id = id
		max_order = order
	state = false
	if find_id > 0:
		# current round fighter
		catch_read[2].data.value = find_id
		# start fighter round
		catch_read[4].get(find_id).value = 1
		# sync fighter round count
		catch_read[3].get(find_id).value = round_count
	else:
		catch_read[1].data.count += 1


#@listenModify(GlobalReady)
#@read(Single<GlobalReady>,Single<GlobalRound>)
func ready(_e, read: Array):
	print("golbal round ready", read[0].data._round)
	if read[0].data._round == read[1].data.count:
		state = true


#when entity create will call this function
#@listenCreate(Entities)
#@read([Multi<RoundCount>, Multi<RoundOrder>, Multi<RoundState>])
func add(e, read: Array):
	print("add entity ", e.id)
	var order = RoundOrder.new()
	order.value = 1
	read[0].insert(e.id, RoundCount.new())
	read[1].insert(e.id, order)
	read[2].insert(e.id, RoundState.new())


#@listenModify(RoundStateC)
#@read([Multi<RoundState>])
func round_over(e, read: Array):
	var round_state = read[0].get(e.id)
	if round_state.value == 1:
		return
	state = true
